package demo2;

import java.util.Random;

public class Work {
    static int count=10_0000_0000;
    static Random random=new Random();
    static int[] arr=new int[count];
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i <count ; i++) {
            arr[i]=random.nextInt(101);
        }
        serial();
        multiThread();

    }
    //单线程的方法
    public static void serial(){
        long sum=0l;
        //开始记录时间
        long start=System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            sum+=arr[i];
        }
//        long sum1=0l;
//        for (int i = 0; i <count ; i+=2) {
//            sum1+=arr[i];
//        }
//        long sum2=0l;
//        for (int i = 1; i <count ; i+=2) {
//            sum2+=arr[i];
//        }
//        sum=sum1+sum2;
        System.out.println("单线程算出来的总和"+sum);
        System.out.println("单线程完成任务耗时： "+(System.currentTimeMillis()-start));

    }

    //多线程的方法
    //multiSum1，2用来传入两个线程求和时候加到这个线程中
    static long multiSum1=0l;
    static long multiSum2=0l;
    public static void multiThread() throws InterruptedException {

        //thread1线程用来求偶数
        Thread thread1 =new Thread(()->{
            for (int i = 0; i <count ; i+=2) {
                multiSum1+=arr[i];
            }
        });
        Thread thread2 =new Thread(()->{
            for (int i = 1; i <count ; i+=2) {
                multiSum2+=arr[i];
            }
        });
        //开始记时间
        long start=System.currentTimeMillis();
        //启动线程
        thread1.start();
        thread2.start();
        //等待两个线程完成任务
        thread1.join();
        thread2.join();
        long multiSum=multiSum1+multiSum2;
        System.out.println("多线程算出来的总和"+multiSum);
        System.out.println("多线程完成任务耗时： "+(System.currentTimeMillis()-start));
    }
}
